async function initJSONFormatter() {

    chrome.storage.sync.get(['autoFormat', 'theme'], (result) => {
        console.log('result', result)        
        // autoFormat,theme
    });

    // 获取原始JSON数据
    const rawJSON = document.body.textContent;

    const isJson = await new Promise(resolve => {
        try {
            JSON.parse(rawJSON)
            resolve(true)
        } catch (error) {
            resolve(false)
        }
    })

    if (!isJson) return

    try {
        const jsonObj = JSON.parse(rawJSON);
        document.body.innerHTML = '';

        // 创建格式化容器
        const container = document.createElement('div');
        container.id = 'json-formatter-container';
        container.style.cssText = `
        font-family: 'Consolas', 'Monaco', monospace;
        padding: 20px;
        background-color: #2d2d2d;
        color: #f8f8f2;
        line-height: 1.5;
        overflow: auto;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
      `;

        // 添加控制面板
        const controls = document.createElement('div');
        controls.style.cssText = `
        display: flex;
        gap: 10px;
        margin-bottom: 15px;
        padding: 10px;
        background: #3c3c3c;
        border-radius: 4px;
      `;

        const expandBtn = document.createElement('button');
        expandBtn.textContent = '全部展开';
        expandBtn.className = 'json-btn';

        const collapseBtn = document.createElement('button');
        collapseBtn.textContent = '全部收起';
        collapseBtn.className = 'json-btn';

        const copyBtn = document.createElement('button');
        copyBtn.textContent = '复制JSON';
        copyBtn.className = 'json-btn';

        controls.appendChild(expandBtn);
        controls.appendChild(collapseBtn);
        controls.appendChild(copyBtn);
        container.appendChild(controls);

        // 添加JSON展示区域
        const jsonViewer = document.createElement('div');
        jsonViewer.id = 'json-viewer';
        container.appendChild(jsonViewer);

        document.body.appendChild(container);
        // document.body.innerHTML = rawJSON

        // 渲染JSON
        renderJSON(jsonObj, jsonViewer);

        // 添加按钮事件
        expandBtn.addEventListener('click', () => {
            expandAll();
        });

        collapseBtn.addEventListener('click', () => {
            collapseAll();
        });

        copyBtn.addEventListener('click', () => {
            navigator.clipboard.writeText(rawJSON);
            copyBtn.textContent = '已复制!';
            setTimeout(() => copyBtn.textContent = '复制JSON', 2000);
        });

        // JSON渲染函数
        function renderJSON(data, container, depth = 0) {
            if (data === null) {
                const nullEl = document.createElement('span');
                nullEl.textContent = 'null';
                nullEl.style.color = '#f92672';
                container.appendChild(nullEl);
                return;
            }

            const type = typeof data;

            if (type === 'boolean' || type === 'number') {
                const el = document.createElement('span');
                el.textContent = data;
                el.style.color = '#ae81ff';
                container.appendChild(el);
                return;
            }

            if (type === 'string') {
                const el = document.createElement('span');
                el.textContent = `"${data}"`;
                el.style.color = '#a6e22e';
                container.appendChild(el);
                return;
            }

            if (Array.isArray(data)) {
                if (data.length === 0) {
                    container.appendChild(document.createTextNode('[]'));
                    return;
                }

                const arrayContainer = document.createElement('div');

                const bracketOpen = document.createElement('span');
                bracketOpen.textContent = '[';
                bracketOpen.style.color = '#f8f8f2';
                arrayContainer.appendChild(bracketOpen);

                const toggleBtn = document.createElement('span');
                toggleBtn.textContent = '−';
                toggleBtn.style.cssText = `
            cursor: pointer;
            margin: 0 5px;
            color: #66d9ef;
            font-weight: bold;
            user-select: none;
          `;
                arrayContainer.appendChild(toggleBtn);

                const itemsContainer = document.createElement('div');
                itemsContainer.style.marginLeft = `${20 * (depth + 1)}px`;
                itemsContainer.className = 'collapsible';

                data.forEach((item, i) => {
                    const itemContainer = document.createElement('div');

                    renderJSON(item, itemContainer, depth + 1);

                    if (i < data.length - 1) {
                        itemContainer.appendChild(document.createTextNode(','));
                    }

                    itemsContainer.appendChild(itemContainer);
                });

                arrayContainer.appendChild(itemsContainer);

                const bracketClose = document.createElement('span');
                bracketClose.textContent = ']';
                bracketClose.style.color = '#f8f8f2';
                arrayContainer.appendChild(bracketClose);

                container.appendChild(arrayContainer);

                // 添加折叠/展开功能
                toggleBtn.addEventListener('click', () => {
                    const isCollapsed = itemsContainer.style.display === 'none';
                    itemsContainer.style.display = isCollapsed ? 'block' : 'none';
                    toggleBtn.textContent = isCollapsed ? '−' : '+';
                });

                return;
            }

            if (type === 'object') {
                const keys = Object.keys(data);
                if (keys.length === 0) {
                    container.appendChild(document.createTextNode('{}'));
                    return;
                }

                const objectContainer = document.createElement('div');

                const braceOpen = document.createElement('span');
                braceOpen.textContent = '{';
                braceOpen.style.color = '#f8f8f2';
                objectContainer.appendChild(braceOpen);

                const toggleBtn = document.createElement('span');
                toggleBtn.textContent = '−';
                toggleBtn.style.cssText = `
            cursor: pointer;
            margin: 0 5px;
            color: #66d9ef;
            font-weight: bold;
            user-select: none;
          `;
                objectContainer.appendChild(toggleBtn);

                const itemsContainer = document.createElement('div');
                itemsContainer.style.marginLeft = `${20 * (depth + 1)}px`;
                itemsContainer.className = 'collapsible';

                keys.forEach((key, i) => {
                    const keyValueContainer = document.createElement('div');

                    // 渲染键
                    const keyEl = document.createElement('span');
                    keyEl.textContent = `"${key}": `;
                    keyEl.style.color = '#f92672';
                    keyValueContainer.appendChild(keyEl);

                    // 渲染值
                    renderJSON(data[key], keyValueContainer, depth + 1);

                    if (i < keys.length - 1) {
                        keyValueContainer.appendChild(document.createTextNode(','));
                    }

                    itemsContainer.appendChild(keyValueContainer);
                });

                objectContainer.appendChild(itemsContainer);

                const braceClose = document.createElement('span');
                braceClose.textContent = '}';
                braceClose.style.color = '#f8f8f2';
                objectContainer.appendChild(braceClose);

                container.appendChild(objectContainer);

                // 添加折叠/展开功能
                toggleBtn.addEventListener('click', () => {
                    const isCollapsed = itemsContainer.style.display === 'none';
                    itemsContainer.style.display = isCollapsed ? 'block' : 'none';
                    toggleBtn.textContent = isCollapsed ? '−' : '+';
                });

                return;
            }
        }

        // 展开全部
        function expandAll() {
            document.querySelectorAll('.collapsible').forEach(el => {
                el.style.display = 'block';
            });
            document.querySelectorAll('#json-viewer span[style*="color: #66d9ef"]').forEach(el => {
                el.textContent = '−';
            });
        }

        // 折叠全部
        function collapseAll() {
            document.querySelectorAll('.collapsible').forEach(el => {
                el.style.display = 'none';
            });
            document.querySelectorAll('#json-viewer span[style*="color: #66d9ef"]').forEach(el => {
                el.textContent = '+';
            });
        }
    } catch (e) {
        console.error('JSON解析错误:', e);
    }
}


// 确保DOM加载完成后执行
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initJSONFormatter);
} else {
    initJSONFormatter();
}